package tech.aichan.AiQA.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import tech.aichan.AiQA.common.DeleteRequest;
import tech.aichan.AiQA.common.ErrorCode;
import tech.aichan.AiQA.constant.CommonConstant;
import tech.aichan.AiQA.exception.ThrowUtils;
import tech.aichan.AiQA.mapper.AppMapper;
import tech.aichan.AiQA.mapper.QuestionMapper;
import tech.aichan.AiQA.mapper.UserMapper;
import tech.aichan.AiQA.model.dto.question.QuestionAddRequest;
import tech.aichan.AiQA.model.dto.question.QuestionContentDTO;
import tech.aichan.AiQA.model.dto.question.QuestionQueryRequest;
import tech.aichan.AiQA.model.dto.question.QuestionUpdateRequest;
import tech.aichan.AiQA.model.entity.App;
import tech.aichan.AiQA.model.entity.Question;
import tech.aichan.AiQA.model.vo.question.QuestionVO;
import tech.aichan.AiQA.service.QuestionService;
import org.springframework.stereotype.Service;
import tech.aichan.AiQA.utils.SqlUtils;
import tech.aichan.AiQA.utils.UserInfoUtil;

import java.util.List;
import java.util.Objects;

/**
* @author AiChan
* @description 针对表【question(题目)】的数据库操作Service实现
* @createDate 2024-05-30 14:15:41
*/
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
    implements QuestionService{

    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private AppMapper appMapper;

    /**
     * 获取查询条件
     *
     * @param questionQueryRequest
     * @return
     */
    public QueryWrapper<Question> getQueryWrapper(QuestionQueryRequest questionQueryRequest) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if (questionQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = questionQueryRequest.getId();
        String questionContent = questionQueryRequest.getQuestionContent();
        Long appId = questionQueryRequest.getAppId();
        Long userId = questionQueryRequest.getUserId();
        Long notId = questionQueryRequest.getNotId();
        String sortField = questionQueryRequest.getSortField();
        String sortOrder = questionQueryRequest.getSortOrder();

        // 补充需要的查询条件
        // 模糊查询
        queryWrapper.like(StrUtil.isNotBlank(questionContent), "questionContent", questionContent);
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(appId), "appId", appId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public void editQuestion(List<QuestionContentDTO> questionContent, Long appId) {
        // 1.判断当前用户是否为创建应用的用户
        App app = appMapper.selectById(appId);
        ThrowUtils.throwIf(!Objects.equals(app.getUserId(), UserInfoUtil.getUserId()), ErrorCode.NO_AUTH_ERROR,"只能修改你创建的应用的题目");
        // 2.修改题目
        Question question = new Question();
        question.setQuestionContent(JSONUtil.toJsonStr(questionContent));
        int i = questionMapper.updateById(question);
        ThrowUtils.throwIf(i != 1, ErrorCode.SYSTEM_ERROR,"请重试");
    }

    @Override
    public Long addQuestion(QuestionAddRequest questionAddRequest) {
        Question question = new Question();
        // 1. 将信息填入question
        question.setAppId(questionAddRequest.getAppId());
        List<QuestionContentDTO> questionContent = questionAddRequest.getQuestionContent();
        question.setQuestionContent(JSONUtil.toJsonStr(questionContent));
        question.setUserId(UserInfoUtil.getUserId());
        // 2. 插入数据库
        int insert = questionMapper.insert(question);
        ThrowUtils.throwIf(insert != 1, ErrorCode.SYSTEM_ERROR,"请重试");
        // 3. 插入Redis TODO
        return question.getId();
    }

    @Override
    public void deleteQuestion(Long id) {
        // 1. 删除数据库
        int i = questionMapper.deleteById(id);
        ThrowUtils.throwIf(i != 1, ErrorCode.SYSTEM_ERROR,"请重试");

        // 2. 删除Redis TODO
    }

    @Override
    public Long updateQuestion(List<QuestionContentDTO> questionContent, Long id) {
        // 1. 构建Question
        Question question = new Question();
        question.setId(id);
        if(questionContent != null && !questionContent.isEmpty()){
            question.setQuestionContent(JSONUtil.toJsonStr(questionContent));
        }
        // 2. 更新数据库
        int i = questionMapper.updateById(question);
        ThrowUtils.throwIf(i != 1, ErrorCode.SYSTEM_ERROR,"请重试");
        // 3. 更新Redis TODO
        return question.getId();
    }

    @Override
    public Page<Question> listPageQuestion(QuestionQueryRequest questionQueryRequest) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 查询数据库
        return this.page(new Page<>(current, size),
                this.getQueryWrapper(questionQueryRequest));
    }

    @Override
    public Page<QuestionVO> listPageQuestionVO(QuestionQueryRequest questionQueryRequest) {
        Page<Question> questionPage = this.listPageQuestion(questionQueryRequest);
        List<Question> records = questionPage.getRecords();
        List<QuestionVO> list = records.stream().map(q -> QuestionVO.getQuestionVOByQuestion(q, userMapper.selectById(q.getUserId()))).toList();
        Page<QuestionVO> result = new Page<>();
        BeanUtil.copyProperties(records,result);
        result.setRecords(list);
        return result;
    }


}




